<?php
/**
 * RSA加密算法
 * @author JohnnyDen <413819942@qq.com>
 * @package \Lib
 * @copyright 2017年12月19日
 */
namespace NMClient\Core\Crypt;

class Rsa {
    
	static private $_private_key = RSA_PRIVATE_KEY;

	static private $_public_key = RSA_PUBLIC_KEY;
	
	static private function _piKey() {
	    static $pi_key;
	    if (!$pi_key) {
	       $pi_key     = openssl_pkey_get_private(self::$_private_key);
	    }
	    return $pi_key;
	}
	
	static private function _puKey() {
	    static $pu_key;
	    if (!$pu_key) {
	        $pu_key    = openssl_pkey_get_public(self::$_public_key);
	    }
	    return $pu_key;
	}
	
	/**
	 * 使用私钥加密数据
	 * @param string $str			待加密字符串
	 */
	static public function privEncrypt($str) {
	    openssl_private_encrypt($str, $encrypted, self::_piKey());
	    return base64_encode($encrypted);
	}
	/**
	 * 使用私钥解密数据
	 * @param string $encrypted		待解密字符串
	 */
	static public function privDecrypt($encrypted) {
	    openssl_private_decrypt(base64_decode($encrypted), $decrypted, self::_piKey());
	    return $decrypted;
	}
	
	/**
	 * 使用公钥加密数据
	 * @param string $str			待加密字符串
	 */
	static public function pubEncrypt($str) {
	    openssl_public_encrypt($str, $encrypted, self::_puKey());
	    return base64_encode($encrypted);
	}
	/**
	 * 使用公钥解密数据
	 * @param string $encrypted		待解密字符串
	 */
	static public function pubDecrypt($encrypted) {
	    openssl_public_decrypt(base64_decode($encrypted), $decrypted, self::_puKey());
	    return $decrypted;
	}
	
	/**
	 * 创建公钥密钥
	 * @return array
	 * <code>
	 * array(private_key, public_key)
	 * </code>
	 */
	static public function creatKey() {
	    $res   = openssl_pkey_new();
	    openssl_pkey_export($res, $private_key);
	    $public_key    = openssl_pkey_get_details($res);
	    $public_key    = $public_key['key'];
	    return array($private_key, $public_key);
	}
	
}